<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-card>
        <template #header> 门店基本信息 </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="门店编码" prop="storageCode">
              <el-input v-model="formData.storageCode" placeholder="请输入门店编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店名称" prop="storageName">
              <el-input v-model="formData.storageName" placeholder="请输入门店名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店类型" prop="storageType">
              <el-input v-model="formData.storageType" placeholder="请输入门店类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="门店金额" prop="storageAmount">
              <el-input-number
                v-model="formData.storageMoney"
                :precision="2"
                :step="0.01"
                placeholder="请输入门店金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店星级" prop="storageStar">
              <el-rate v-model="formData.storageStar" :max="5" show-score />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="东东管家星级" prop="housekeeperStar">
              <el-rate v-model="formData.housekeeperStar" :max="5" show-score />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="地址" prop="city">
              <el-cascader
                v-model="cityArr"
                :options="areaList"
                :props="props"
                @change="handleChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="门店地址" prop="storageAddress">
              <el-input v-model="formData.storageAddress" placeholder="请输入门店地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="经度" prop="longitude">
              <el-input-number
                v-model="formData.longitude"
                :precision="6"
                placeholder="请输入经度"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number
                v-model="formData.latitude"
                :precision="6"
                placeholder="请输入纬度"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客服热线" prop="serviceHotline">
              <el-input v-model="formData.serviceHotline" placeholder="请输入客服热线" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin-top: 20px">
        <template #header> 促销信息 </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="限时折扣" prop="promotionalDiscount">
              <el-input v-model="formData.promotionalDiscount" placeholder="请输入限时折扣" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="促销开始时间" prop="promotionStartTime">
              <el-date-picker
                v-model="formData.promotionalStartTime"
                type="datetime"
                placeholder="请选择促销开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="x"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="促销结束时间" prop="promotionEndTime">
              <el-date-picker
                v-model="formData.promotionalEndTime"
                type="datetime"
                placeholder="请选择促销结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                value-format="x"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="促销详情" prop="promotionalDetails">
              <el-input
                v-model="formData.promotionalDetails"
                type="textarea"
                placeholder="请输入促销详情"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin-top: 20px">
        <template #header> 联系信息 </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系人名称" prop="contactName">
              <el-input v-model="formData.contactName" placeholder="请输入联系人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactMobileNo">
              <el-input v-model="formData.contactMobileNo" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="enable">
              <el-radio-group v-model="formData.enable">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { BaseStorageApi, BaseStorageVO } from '@/api/crm/basestorage'
import * as AreaApi from '@/api/system/area'

/** 门店表单 */
defineOptions({ name: 'BaseStorageForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 省市区相关数据
const areaList = ref<Tree[]>([])
const cityArr = ref<number[]>([])

const props = {
  value: 'id',
  label: 'name'
}
// 扩展 BaseStorageVO 接口，允许日期字段为字符串（因为使用了 value-format）
interface FormData extends BaseStorageVO {
  // 保持与 BaseStorageVO 一致，因为使用了 value-format，日期选择器会返回字符串
}

const formData = ref<FormData>({
  storageId: 0,
  storageCode: '',
  storageName: '',
  storageAddress: '',
  storageType: '',
  storageMoney: 0,
  storageStar: 0,
  housekeeperStar: 0,
  serviceHotline: '',
  provinceId: 0,
  provinceName: '',
  cityId: 0,
  cityName: '',
  regionId: 0,
  regionName: '',
  longitude: 0,
  latitude: 0,
  promotionalDiscount: '',
  promotionalStartTime: '',
  promotionalEndTime: '',
  promotionalDetails: '',
  contactName: '',
  contactMobileNo: '',
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: '',
  remark: '',
  enable: 1
})
const formRef = ref() // 表单 Ref

/** 表单校验 */
const formRules = reactive({
  storageCode: [{ required: true, message: '门店编码不能为空', trigger: 'blur' }],
  storageName: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
  storageAddress: [{ required: true, message: '门店地址不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '联系人名称不能为空', trigger: 'blur' }],
  contactMobileNo: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  enable: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 加载省市区数据
  areaList.value = await AreaApi.getAreaTree()
  cityArr.value = []

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BaseStorageApi.getBaseStorage(id)

      // 设置省市区选择器的值
      if (formData.value.provinceId) {
        cityArr.value.push(formData.value.provinceId)
      }
      if (formData.value.cityId) {
        cityArr.value.push(formData.value.cityId)
      }
      if (formData.value.regionId) {
        cityArr.value.push(formData.value.regionId)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 省市区选择器变化处理 */
const handleChange = (value: number[]) => {
  console.log('省市区选择值:', value)
  if (value && value.length > 0) {
    // 保存ID
    formData.value.provinceId = value[0] || 0
    formData.value.cityId = value[1] || 0
    formData.value.regionId = value[2] || 0

    // 根据ID获取对应的名称
    const province = areaList.value.find((item) => item.id === value[0])
    const city = province?.children?.find((item) => item.id === value[1])
    const region = city?.children?.find((item) => item.id === value[2])

    // 保存名称
    formData.value.provinceName = province?.name || ''
    formData.value.cityName = city?.name || ''
    formData.value.regionName = region?.name || ''
  } else {
    // 清空所有值
    formData.value.provinceId = 0
    formData.value.provinceName = ''
    formData.value.cityId = 0
    formData.value.cityName = ''
    formData.value.regionId = 0
    formData.value.regionName = ''
  }
  console.log('表单数据:', formData.value)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BaseStorageVO
    if (formType.value === 'create') {
      await BaseStorageApi.createBaseStorage(data)
      message.success(t('common.createSuccess'))
    } else {
      await BaseStorageApi.updateBaseStorage(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    storageId: 0,
    storageCode: '',
    storageName: '',
    storageAddress: '',
    storageType: '',
    storageMoney: 0,
    storageStar: 0,
    housekeeperStar: 0,
    serviceHotline: '',
    provinceId: 0,
    provinceName: '',
    cityId: 0,
    cityName: '',
    regionId: 0,
    regionName: '',
    longitude: 0,
    latitude: 0,
    promotionalDiscount: '',
    promotionalStartTime: '',
    promotionalEndTime: '',
    promotionalDetails: '',
    contactName: '',
    contactMobileNo: '',
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: '',
    remark: '',
    enable: 1
  } as FormData
  cityArr.value = []
  formRef.value?.resetFields()
}
</script>
